#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
    CMakeLists.txt生成器
'''

# ---------------------------------------------------------------------
# 文件操作
#

import os
CODING = 'UTF8'

def yy_file_read_bytes(filename):
    assert(os.path.isfile(filename)), filename
    return open(filename, 'rb').read()

def yy_file_read_content(filename, coding=CODING):
    assert(os.path.isfile(filename)), filename
    data = yy_file_read_bytes(filename)
    return data.decode(coding)

def yy_file_write_bytes(filename, data):
    fp = open(filename, 'wb')
    fp.write(data)
    fp.close()

def yy_file_write_content(filename, content, coding=CODING):
    yy_file_write_bytes(filename, content.encode(coding))

    
# ---------------------------------------------------------------------
# CMake文件解析
#

ADD_SUBDIRECTORY_TAG = 'ADD_SUBDIRECTORY('

def cmake_get_add_subdirectories_from_content(content):
    contents = content.replace('\r', '')
    subdirs = []
    tag = ADD_SUBDIRECTORY_TAG
    tag_len = len(tag)
    for line in contents.split('\n'):
        if tag in line:
            subdirs.append(line.strip()[tag_len:-1])
    return subdirs

def cmake_get_add_subdirectories(cmake_template_file):
    return cmake_get_add_subdirectories_from_content(yy_file_read_content(cmake_template_file))

def find_latest_subdirectories(rootdir, subdirs):
    subdirs_dict = {}
    for item in os.listdir(rootdir):
        path_name = os.path.join(rootdir, item)
        if os.path.isdir(path_name):
            for subdir in subdirs:
                if item.startswith(subdir):
                    if subdir not in subdirs_dict:
                        subdirs_dict[subdir] = []
                    subdirs_dict[subdir].append(item)
    return subdirs_dict

def cmake_update_subdirectories(rootdir, cmake_template_file, cmake_output_file):
    content = yy_file_read_content(cmake_template_file).replace('\r', '')
    subdirs = cmake_get_add_subdirectories_from_content(content)
    subdirs_dict = find_latest_subdirectories(rootdir, subdirs)
    
    variables = []
    for tag in subdirs:
        if tag in subdirs_dict:
            latest = subdirs_dict[tag][-1]
            content = content.replace('%s%s)' % (ADD_SUBDIRECTORY_TAG, tag), '%s%s)' % (ADD_SUBDIRECTORY_TAG, latest))
            variables.append('SET(%s_SOURCE_DIR "%s")' % (tag.upper(), os.path.join(rootdir, latest).replace('\\', '/')))
    variables.append('')
    variables.insert(0, content)
    yy_file_write_content(cmake_output_file, '\n'.join(variables))
            

if __name__ == '__main__':
    rootdir = os.path.dirname(__file__)
    cmake_update_subdirectories(rootdir, "CMakeLists.txt.in", "CMakeLists.txt.bak")
    print('输出完成')
